<template>
  <div class="sellBox">
    <div class="sellmain mg-20">
      <!-- left -->
      <div class="sellmain_l flex-1 mgr-20">
        <div class="back">
          <el-button
            icon="el-icon-back"
            class="color-0 bg-theme fontW-7 font-28 box-4 text-s"
            @click="back"
            type="primary">{{ $t("btn.cancel") }}</el-button>
        </div>
        <div class="img mgt-30">
          <div class="imgItem border-3-ff bd-r-10 pd-10">
            <img class="bd-r-10" :src="infoData.image_url" alt="">
          </div>
        </div>
      </div>
      <!-- right -->
      <div class="sellmain_r flex-1">
        <div class="sell_title">
          <p class="theme-color font-36 fontW-b font-f-ib">{{$t('sell.title')}}</p>
        </div>
        <div class="sell_type mgt-20">
          <div class="theme-color font-24 fontW-b font-f-ib">{{$t('title.type')}}</div>
          <div class="flex sellItem">
            <div @click="chooseSellType(1)" :class="sellType===1?'bg-theme boxS-i-4':'bg-f box-4'" class="item bd-r-10 font-20 fontW-b font-f-ib text-c">{{$t('sell.fixed_price')}}</div>
            <div @click="chooseSellType(2)" :class="sellType===2?'bg-theme boxS-i-4':'bg-f box-4'" class="item bd-r-10 font-20 fontW-b font-f-ib text-c">{{$t('sell.auction')}}</div>
          </div>
          <div class="mgt-10" v-if="sellType === 0">
            <p class="color-ffc4 font-f-iR fontW-n font-18">{{$t('sell.tips')}}</p>
          </div>
          <div class="chainBox flex mgt-20">
            <!-- <div class="flex-1">
              <div class="theme-color font-24 fontW-b font-f-ib">{{$t('sell.chain')}}</div>
              <div class="sellIcon flex-left-nowrap bg-theme border-r">
                <div class="sellIconItem mgl-13"><img src="../../assets/ETH/ETH.svg" alt=""></div>
                <div class="font-20 fontW-b font-f-ib flex-1">
                  <Select :options="selectData" @getSelectVal="getSelectVal"/>
                </div>
              </div>
            </div> -->
            <div class="flex-1">
              <div class="theme-color font-24 fontW-b font-f-ib">{{$t('sell.set_price')}}</div>
              <div class="priceBox bg-69 font-20 border-r">
                <input class="color-d6 pdr-10 text-l pdl-10" v-model="price" type="text" placeholder="33">
              </div>
            </div>
          </div>
          <div class="mgt-20 flex-s-between">
            <div class="color-ffc4 font-24 fontW-b font-f-ib">{{$t('sell.allow_group_buying')}}</div>
            <div>
              <span v-if="AllowGroupBuy" class="color-f font-14 fontW-b font-f-ib">{{$t('sell.groupSoldQuicker')}}</span>
              <el-switch
                @change="hundleAllowGroupBuy"
                v-model="AllowGroupBuy"
                active-color="#FE66C4"
                inactive-color="#aaaaaa">
              </el-switch>
            </div>
          </div>
          <!-- 允许被团购 -->
          <div v-if="AllowGroupBuy">
            <div class="chainBox flex mgt-20">
              <div class="flex-2">
                <div class="color-f font-15 fontW-b font-f-ib">{{$t('sell.groupBuyImn')}}</div>
                <div class="sellIcon flex-left-nowrap bg-theme border-r">
                  <div class="sellIconItem mgl-13"><img src="../../assets/ETH/IMEETNFT.svg" alt=""></div>
                  <div class="font-20 fontW-b font-f-ib">IMN</div>
                </div>
              </div>
              <div class="flex-3">
                <div class="mgl-13 color-f font-15 fontW-b font-f-ib text-r">{{$t('sell.SetGroupPrice')}}</div>
                <div class="mgl-13 priceBox bg-69 font-20 border-r">
                  <input class="color-d6 pdr-10 text-r" type="text" placeholder="33">
                </div>
              </div>
            </div>
            <div class="mgt-10 flex-s-between">
              <div class="color-f font-15 fontW-b font-f-ib">{{$t('sell.GroupCannotChange')}}</div>
              <div class="bg-ffc4 h-33 font-15 fontW-b font-f-ib pdlr-10 border-r box-4">{{$t('sell.automatic')}}</div>
            </div>
          </div>
          <div class="calendar flex mgt-20">
            <div class="flex-1">
              <div class="theme-color font-24 fontW-b font-f-ib">{{$t('sell.starttime')}}</div>
              <div class="calendarItem bg-69 font-20 border-r">
                <calendar :dateType="dateType" :pickerOptions="pickerOptions" @getTimer="getTimerStart"/>
              </div>
            </div>
            <div class="flex-1">
              <div class="mgl-13 theme-color font-24 fontW-b font-f-ib">{{$t('sell.endtime')}}</div>
              <div class="mgl-13 calendarItem bg-69 font-20 border-r">
                <calendar :dateType="dateType" :pickerOptions="pickerOptionsEnd" @getTimer="getTimerEnd"/>
              </div>
            </div>
          </div>
          <div v-if="AllowGroupBuy" class="color-f font-15 fontW-b font-f-ib">{{$t('sell.lessDay')}}</div>
          <div v-if="!AllowGroupBuy" class="mgt-20 flex-s-between">
            <div class="theme-color font-24 fontW-b font-f-ib">{{$t('sell.sale_designated_address')}}</div>
            <div>
              <el-switch
                @change="hundleAddress"
                v-model="designatedAddressFlag"
                active-color="#04ff00"
                inactive-color="#aaaaaa">
              </el-switch>
            </div>
          </div>
          <div v-if="!AllowGroupBuy" class="allowAddress mgt-20 bg-69 font-20 border-r">
            <input class="pd-5 color-d6" type="text" v-model="designatedAddress" placeholder="0x372a...to2e">
          </div>
          <div v-if="!AllowGroupBuy" class="mgt-10">
            <p class="font-f-iR font-20 color-c8">{{$t('sell.groupBuyTips')}}</p>
          </div>
          <div class="submit mgt-100" :class="AllowGroupBuy? '':' bd_t-2_d8'">
            <p v-if="AllowGroupBuy" class="pdb-10 bd_b-2_d8 color-f font-15 fontW-b font-f-ib">{{$t('sell.groupInstructions')}}</p>
            <p class="color-d6 mgt-10">{{$t('sell.PlatformServicefee')}} <span class="mgl-13">2.5%</span></p>
            <div class="mgt-10">
              <el-button
                class="color-0 bg-theme fontW-7 font-28 box-4 text-s"
                type="primary"
                @click="submitNext"
              >{{ $t("btn.nextStep") }}</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Calendar from '../../components/component/Calendar'
import Select from '../../components/component/Select'
import {initContract, initWeb3} from '../../../static/contract/createContract'
import contractAddress from '../../../static/contract/contractAddress'
import web3Sign from '../../Js/web3Sign'
const selectData = [
  {id: 0, value: 'ETH'},
  {id: 1, value: 'WETH'},
  {id: 2, value: 'Polygon'},
  {id: 3, value: 'Matic'}
]
export default {
  name: 'sell',
  components: {
    Calendar,
    Select
  },
  data () {
    return {
      infoData: null,
      sellType: 0,
      price: '',
      AllowGroupBuy: false,
      startTime: '',
      endTime: '',
      dateType: 'datetime',
      designatedAddressFlag: false,
      designatedAddress: '',
      selectData: selectData,
      web3: {},
      ERC20Contract: null,
      makerOrder: null,
      takerOrder: null,
      ImeetExchangeContract: null,
      strategy: '',
      ZERO_ADDRESS: '0x0000000000000000000000000000000000000000',
      pickerOptions: { // 开始时间禁用小于当前时间
        disabledDate (date) {
          let zero = new Date().setHours(0, 0, 0, 0)
          if (date.getTime() < zero) {
            return true
          }
          return false
        }
      },
      pickerOptionsEnd: { // 时间禁用小于当前时间大于两个月后时间
        disabledDate: (time) => {
          const day60 = 60 * 24 * 3600 * 1000
          return (time.getTime() < Date.now() - 8.64e6 || time.getTime() > Date.now() + day60)
        }
      }
    }
  },
  created () {
    this.web3 = initWeb3()
    let contractObj = initContract()
    console.log(contractObj, this.web3, contractAddress) // 合约初始化
    this.ImeetERC20Contract = contractObj.ImeetERC20Contract
    this.ImeetExchangeContract = contractObj.ImeetExchangeContract
    console.log(this.ImeetERC20Contract)
    this.getDetails()
    this.getStrategy()
    /**
     * 签名并获取签名哈希
     * @param {number} isOrderAsk 0 maker 1 taker
     * @param {number} price
     * @param {number} tokenId
     */
    // web3Sign.subSign(1, 1, 0)
    //   .then(data => {
    //     console.log('web3Sign:', data)
    //   })
  },
  methods: {
    /**
     * 查询艺术品详情
     * @param {id} 艺术品ID
    */
    getDetails: function () {
      this.$loading.show()
      const params = {
        // collectionAddress: this.$route.query.CollectionAddress,
        id: this.$route.query.artId
      }
      this.$Api.Collection.getCollectionArtDetail(params)
        .then((res) => {
          this.$loading.hide()
          console.log(res, 'getDetails', JSON.stringify(res))
          if (res && res.code === 200) {
            this.infoData = res.data.asset
            // console.log(this.infoData, res.data)
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'getDetails', JSON.stringify(err))
        })
    },
    getStrategy: function () {
      this.$loading.show()
      this.$Api.Common.getStrategy()
        .then((res) => {
          this.$loading.hide()
          console.log(res, 'getStrategy', JSON.stringify(res))
          this.strategy = res.data[0].Address
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'getStrategy,err', JSON.stringify(err))
        })
    },
    chooseSellType: function (type) {
      this.sellType = type
    },
    back: function () {
      this.$router.go(-1)
    },
    hundleAllowGroupBuy: function (val) {
      console.log(val)
    },
    hundleAddress: function () {
      console.log(this.designatedAddressFlag, 'll')
    },
    getTimerStart: function (timer) {
      // console.log(timer, 's')
      this.startTime = timer / 1000
    },
    getTimerEnd: function (timer) {
      // console.log(timer, 'e')
      this.endTime = timer / 1000
    },
    getSelectVal: function (val) {
      console.log(val)
    },
    submitNext: function () {
      // console.log(this.strategy, this.price, this.startTime, this.endTime)
      const params = {
        isOrderAsk: 1,
        strategy: this.strategy,
        price: this.price,
        startTime: this.startTime,
        endTime: this.endTime,
        designatedAddressFlag: this.designatedAddressFlag,
        designatedAddress: this.designatedAddress,
        tokenId: Number(this.infoData.TokenId)
      }
      web3Sign.subSign(params)
        .then(data => {
          console.log('web3Sign:', data)
          this.submitMakeOrder(data)
        })
        .catch(err => {
          console.log('web3Sign:', err)
        })
    },
    submitMakeOrder: function (signHash) {
      let ParamsVal = ''
      if (this.designatedAddressFlag) {
        ParamsVal = this.designatedAddress
      } else {
        ParamsVal = this.ZERO_ADDRESS
      }
      const params = {
        Signature: signHash,
        IsOrderAsk: 1,
        Signer: this.$cookies.get('wallet_acount'),
        CollectionAddress: this.infoData.CollectionAddress,
        Price: Number(this.price),
        TokenId: this.infoData.TokenId,
        Amount: 1,
        StrategyAddress: this.strategy,
        CurrencyAddress: contractAddress.ImeetERC20Address.toLowerCase(),
        Nonce: Number(this.infoData.TokenId),
        StartTime: this.startTime,
        EndTime: this.endTime,
        MinPercentageToAsk: 9000,
        Params: ParamsVal
      }
      this.$loading.show()
      this.$Api.Order.makerOrder(params)
        .then((res) => {
          this.$loading.hide()
          console.log(res, 'makerOrder', JSON.stringify(res))
          this.$router.push({
            path: '/person_collection',
            query: {
              type: 1
            }
          })
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'makerOrder,err', JSON.stringify(err))
        })
    },
    sign1: function () {
      this.ApproveSubmit()
    },
    sign: async function () {
      // const maker = '0xf2fa535cba30f55803723fed9653281e2d1c2a01'
      // const isOrderAsk = 1
      // const signer = maker
      // const collection = '0x08e73f11e14c00d83edeb7c2adaa31a07383870b'
      // const price = web3.utils.toWei('100','ether')
      // const tokenId = 2
      // const amount = 1
      // const strategy = '0xa72b4513f8ce264029328950545d0df508bf26aa'
      // const currency = '0x90cadbe45eba7dba90fc0d050e81b3a4c8ea9004'
      // const nonce = 1
      // const startTime = 1652601974
      // const endTime = 1652612074
      // const minPercentageToAsk = 9000

      // console.log(this.ImeetExchangeContract)
      const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
      const user = '0xf2fa535cba30f55803723fed9653281e2d1c2a01'.toLowerCase()
      const isOrderAsk = 1
      const signer = user
      const collection = contractAddress.ERC721Address.toLowerCase()
      const price = this.web3.utils.toWei('100', 'ether')
      const tokenId = 4
      const amount = 1
      const strategy = '0xa72b4513F8ce264029328950545D0DF508BF26Aa'.toLowerCase()
      const currency = contractAddress.ERC20Address.toLowerCase()
      const nonce = 3
      const startTime = Math.floor(Date.now() / 1000) - 100
      // const startTime = 1652601974
      const endTime = Math.floor(Date.now() / 1000) + 10000
      // const endTime = 1652612074
      const minPercentageToAsk = 9000
      var Params = ZERO_ADDRESS
      var paramsHash = this.web3.utils.soliditySha3(Params)
      const MAKER_ORDER_HASH =
        '0x40261ade532fa1d2c7293df30aaadb9b3c616fae525a0b56d3d411c841a85028'.toLowerCase()
      console.log('paramsHash: ', paramsHash)
      var typeHash = this.web3.utils.soliditySha3(
        'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
      )
      console.log('typeHash: ', typeHash)
      this.makerOrder = {
        isOrderAsk: isOrderAsk,
        signer: signer,
        collection: collection,
        price: price,
        tokenId: tokenId,
        amount: amount,
        strategy: strategy,
        currency: currency,
        nonce: nonce,
        startTime: startTime,
        endTime: endTime,
        minPercentageToAsk: minPercentageToAsk,
        params: Params
      }
      console.log(this.makerOrder, 'this.makerOrder')
      var hashMsg = this.web3.utils.soliditySha3(
        { t: 'bytes32', v: MAKER_ORDER_HASH },
        { t: 'uint256', v: isOrderAsk },
        { t: 'uint256', v: signer },
        { t: 'uint256', v: collection },
        { t: 'uint256', v: price },
        { t: 'uint256', v: tokenId },
        { t: 'uint256', v: amount },
        { t: 'uint256', v: strategy },
        { t: 'uint256', v: currency },
        { t: 'uint256', v: nonce },
        { t: 'uint256', v: startTime },
        { t: 'uint256', v: endTime },
        { t: 'uint256', v: minPercentageToAsk },
        { t: 'bytes32', v: paramsHash }
      )
      console.log('hashMsg:', hashMsg)

      const msgParams = JSON.stringify({
        domain: {
          chainId: 1337,
          name: 'ImeetNFT',
          verifyingContract: '0x440623AF74020355c6da6bc32D55f6ED89c26390',
          version: '1'
        },
        message: {
          orderhash: hashMsg
        },
        primaryType: 'OrderHash',
        types: {
          EIP712Domain: [
            { name: 'name', type: 'string' },
            { name: 'version', type: 'string' },
            { name: 'chainId', type: 'uint256' },
            { name: 'verifyingContract', type: 'address' }
          ],
          OrderHash: [
            {name: 'orderhash', type: 'bytes32'}
          ]
        }
      })

      // console.log(msgParams)

      var from = this.$cookies.get('wallet_acount')
      // 使用eth_signTypedData_V4结构化签名方法，这里只对最终哈希结构化
      var params = [from, msgParams]
      var method = 'eth_signTypedData_v4'
      console.log(from, params, method, ';;;;;')

      this.web3.currentProvider.sendAsync(
        { method, params, from },
        (err, result) => {
          console.log(err, result, 'currentProvider')
          this.makerOrder = {
            isOrderAsk: isOrderAsk,
            signer: signer,
            collection: collection,
            price: price,
            tokenId: tokenId,
            amount: amount,
            strategy: strategy,
            currency: currency,
            nonce: nonce,
            startTime: startTime,
            endTime: endTime,
            minPercentageToAsk: minPercentageToAsk,
            params: Params,
            signature: result.result
          }
          this.takerOrder = {
            isOrderAsk: isOrderAsk,
            taker: '0xBb9B30B5D9c8355AcB0d248be49234a728d51fDF',
            price: price,
            tokenId: tokenId,
            minPercentageToAsk: minPercentageToAsk,
            params: new Uint8Array(1)
          }
          console.log(this.makerOrder, 'maker', JSON.stringify(this.makerOrder))
          console.error(this.takerOrder, 'taker')
          // this.ImeetExchangeContract.methods.matchAskWithTakerBid(this.takerOrder, this.makerOrder).send({from: from},function(error, transactionHash){
          //   console.log(error,transactionHash)
          // })
          // this.ApproveSubmit()
        }
      )
    },
    ApproveSubmit: async function() {
      this.makerOrder = {
        'isOrderAsk': 1,
        'signer': '0xf2fa535cba30f55803723fed9653281e2d1c2a01',
        'collection': '0x08e73f11e14c00d83edEB7c2ADaA31A07383870B',
        'price': '100000000000000000000',
        'tokenId': 4,
        'amount': 1,
        'strategy': '0xa72b4513F8ce264029328950545D0DF508BF26Aa',
        'currency': '0x90CAdBE45eBa7DbA90fC0d050E81B3A4c8eA9004',
        'nonce': 3,
        'startTime': 1652608944,
        'endTime': 1652619044,
        'minPercentageToAsk': 9000,
        'params': '0x0000000000000000000000000000000000000000',
        'signature': '0x7c84ef329b604acc3aa9798be776f5e580cbd7f01355b81f54d1fff7abbbcede405096e1ad0c415de4d3cd3041d48b93591b4ec0ce7ccc1e0ea9c2c888df18661c'
      }
      await this.ImeetERC20Contract.methods
        .approve(contractAddress.ImeetExchangeAddress, this.web3.utils.toWei('10000', 'ether'))
        .send({from: this.$cookies.get('wallet_acount')}, (err, res) => {
          console.log(err, res, 'approve')
          if (res) {
            this.submitSign()
          } else {
            console.log('approve.err:' + err)
          }
        })
    },
    submitSign: function () {
      const from = this.$cookies.get('wallet_acount')
      this.takerOrder = {
        isOrderAsk: 0,
        taker: '0xBb9B30B5D9c8355AcB0d248be49234a728d51fDF',
        price: this.web3.utils.toWei('100', 'ether'),
        tokenId: 4,
        minPercentageToAsk: 9000,
        params: new Uint8Array(1)
      }
      console.log(this.takerOrder, this.makerOrder)
      this.ImeetExchangeContract.methods.matchAskWithTakerBid(this.takerOrder, this.makerOrder)
        .send({from: from}, (error, transactionHash) => {
          console.log(error, transactionHash)
        })
    }
  }
}
</script>
<style lang="less" scoped>
.sellBox {
  width: 100%;
  height: auto;
  overflow: hidden;
  .sellmain {
    width: 70%;
    height: auto;
    display: flex;
    .sellmain_l {
      .back {
        /deep/.el-button--primary {
          width: 264px;
          background: #7de9ff;
          border: none;
          i {
            display: block;
            float: left!important;
            font-weight: 900;
            border: 3px solid;
            border-radius: 50%;
            box-sizing: border-box;
          }
        }
      }
      .img {
        .imgItem {
          display: inline-block;
          width: 80%;
          overflow: hidden;
          img {
            width: 100%;
          }
        }
      }
    }
    .sellmain_r {
      .sell_type {
        .sellItem {
          .item {
            width: 126px;
            height: 48px;
            line-height: 48px;
          }
          .item:nth-child(2) {
            margin-left: 5px;
          }
        }
        .chainBox {
          .sellIcon {
            height: 33px;
            .sellIconItem {
              img {
                width: 25px;
                height: 25px;
              }
            }
          }
          .priceBox {
            height: 33px;
            input {
              width: 100%;
              height: 100%;
              background: none;
            }
          }
        }
        .allowAddress {
          input {
            width: 100%;
            height: 100%;
            background: none;
          }
        }
        .submit {
          /deep/.el-button--primary {
            width: 264px;
            background: #7de9ff;
            border: none;
          }
        }
      }
    }
  }
}
</style>
